Page({
    data: {
      bannerImages: [],
      title: "",
      score: 0, // 加权后的最终分数
      originalScore: 0, // 课程原始分数
      userScoreAvg: 0, // 用户平均分数
      author: "",
      participant: 0,
      videos: [],
      reviews: [],
      isBannerZoom: false,
      autoPlay: true,
      showVideoModal: false,
      currentVideoIndex: 0,
      currentRate: 1.0,
      currentRateIndex: 1,
      playbackRates: [0.5, 1.0, 1.5, 2.0],
      showActionBtns: false, 
      reviewPath: "/pages/review/review",
      testPath: "/pages/test/test",
      videoContext: null,
      rawVideoDurations: [],
      videoObjectFit: "cover",
      showVipConfirmModal: false, 
      showVipTipModal: false,     
      isVip: false,
      showReviewModal: false, 
      commentContent: "", 
      courseId: null,
      isRefreshing: false,
      // 评分相关
      showScoreModal: false,
      selectedScore: 0,
      hasEvaluated: false, // 是否已评价
      // Vant评分组件配置
      rateCount: 5,        // 星星数量
      rateSize: 40         // 星星大小(rpx)
    },
  
    onLoad(options) {
      const courseId = options.id;
      this.setData({ courseId });
      
      const system = wx.getSystemInfoSync().system;
      this.setData({
        videoObjectFit: system.includes("Android") ? "fillCrop" : "cover"
      });
      this.fetchCourseDetail(courseId);
      this.checkVipStatus();
      this.checkUserEvaluationStatus(courseId); // 检查用户是否已评价
    },
  
    // 检查用户是否已评价该课程
    checkUserEvaluationStatus(courseId) {
      const userInfo = wx.getStorageSync('userInfo') || {};
      const userId = userInfo.id;
      const token = wx.getStorageSync('token') || '';
  
      if (!userId ||!token) return;
  
      wx.request({
        url: `http://localhost:8080/course/score/check`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`,
          'content-type': 'application/json'
        },
        data: {
          userId: userId,
          coursesId: courseId
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            this.setData({
              hasEvaluated: res.data.data.hasEvaluated, 
              selectedScore: res.data.data.score || 0
            });
          }
        },
        fail: (err) => {
          console.error('检查评价状态失败:', err);
        }
      });
    },
  
    checkVipStatus() {
      const userInfo = wx.getStorageSync('userInfo') || {};
      const isVip = userInfo.isVip || false;
      this.setData({ isVip });
    },
  
    fetchCourseDetail(courseId, forceRefresh = false) {
      if (this.data.isRefreshing &&!forceRefresh) return;
  
      this.setData({ isRefreshing: true });
      const token = wx.getStorageSync('token') || '';
      
      wx.request({
        url: `http://localhost:8080/course/courses/Detail/${courseId}`,
        method: 'GET',
        header: { 
          'Authorization': `Bearer ${token}`,
          'Cache-Control': 'no-cache'
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            const courseData = res.data.data;

            // 计算加权平均分数（课程分数60% + 用户评分平均值40%）
            const originalScore = courseData.score || 0;
            const userScores = courseData.userCourseScore || [];
            
            // 计算用户评分平均值
            let userScoreAvg = 0;
            if (userScores.length > 0) {
              const total = userScores.reduce((sum, item) => sum + (item.score || 0), 0);
              userScoreAvg = total / userScores.length;
            }
            
            // 计算加权分数并保留一位小数
            const weightedScore = (originalScore * 0.6 + userScoreAvg * 0.4).toFixed(1);
  
            const bannerImages = [];
            const coverImage = courseData.images.find(img => img.description === '封面图');
            if (coverImage) {
              bannerImages.push(`https://gzq123.oss-cn-beijing.aliyuncs.com/${coverImage.imgUrl}`);
            }
            const carouselImages = courseData.images
             .filter(img => img.description.startsWith('轮播图'))
             .map(img => `https://gzq123.oss-cn-beijing.aliyuncs.com/${img.imgUrl}`);
            bannerImages.push(...carouselImages);
  
            const adaptedVideos = courseData.videos.map(video => {
              let seconds = 0;
              if (video.duration) {
                const timeParts = video.duration.split(':').map(Number);
                if (timeParts.length === 3) {
                  seconds = timeParts[0] * 3600 + timeParts[1] * 60 + timeParts[2];
                } else if (timeParts.length === 2) {
                  seconds = timeParts[0] * 60 + timeParts[1];
                }
              }
  
              return {
                id: video.id,
                title: video.title,
                url: `https://gzq123.oss-cn-beijing.aliyuncs.com/${video.videoUrl}`,
                duration: this.formatDuration(seconds),
                rawDuration: seconds
              };
            });
  
            const sortedComments = (courseData.comments || []).sort((a, b) => {
              return new Date(b.createTime) - new Date(a.createTime);
            }).map(comment => ({
              id: comment.id,
              author: comment.users?.nickname || '匿名用户',
              date: this.formatDate(comment.createTime),
              content: comment.content,
            }));
  
            this.setData({
              bannerImages: bannerImages,
              title: courseData.title,
              score: weightedScore, // 显示加权后的分数
              originalScore: originalScore,
              userScoreAvg: userScoreAvg.toFixed(1),
              author: courseData.users?.nickname || '未知作者',
              participant: courseData.participantCount || 0,
              videos: adaptedVideos,
              rawVideoDurations: adaptedVideos.map(v => v.rawDuration),
              reviews: sortedComments,
            });
          } else {
            wx.showToast({ title: '数据获取失败', icon: 'none' });
            console.error('课程详情接口异常：', res);
          }
        },
        fail: (err) => {
          wx.showToast({ title: '请求失败', icon: 'none' });
          console.error('课程详情接口请求失败：', err);
        },
        complete: () => {
          this.setData({ isRefreshing: false });
        }
      });
    },
  
    formatDuration(seconds) {
      if (isNaN(seconds) || seconds < 0) return '00:00';
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = Math.floor(seconds % 60);
  
      if (hours > 0) {
        return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
      } else {
        return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
      }
    },
  
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
  
    openVideoModal(e) {
      if (!this.data.isVip) {
        this.setData({ showVipTipModal: true });
        return;
      }
  
      const index = e.currentTarget.dataset.index;
      this.setData({ showVideoModal: false }, () => {
        this.setData({
          showVideoModal: true,
          currentVideoIndex: index
        }, () => {
          setTimeout(() => {
            this.videoContext = wx.createVideoContext("videoPlayer", this);
            if (this.videoContext) {
              this.videoContext.play();
              setTimeout(() => {
                this.videoContext.pause();
              }, 100);
            } else {
              console.error("视频上下文创建失败");
              wx.showToast({ title: "视频加载失败", icon: "none" });
            }
          }, 600);
        });
      });
    },
  
    onLoadedMetadata(e) {
      const realDuration = e.detail.duration;
      const { currentVideoIndex, videos, rawVideoDurations } = this.data;
  
      if (rawVideoDurations[currentVideoIndex] <= 0 ||
        Math.abs(realDuration - rawVideoDurations[currentVideoIndex]) > 2) {
        const updatedVideos = [...videos];
        updatedVideos[currentVideoIndex].duration = this.formatDuration(realDuration);
        this.setData({ videos: updatedVideos });
      }
    },
  
    closeVideoModal() {
      if (this.videoContext) {
        this.videoContext.stop();
        this.videoContext.seek(0);
        this.videoContext = null;
      }
      this.setData({ showVideoModal: false });
    },
  
    onVideoEnded() {
      const { currentVideoIndex, videos, hasEvaluated } = this.data;
      if (currentVideoIndex === videos.length - 1) {
        setTimeout(() => {
          this.closeVideoModal();
          this.setData({ showActionBtns: true });
          
          // 如果未评价，显示评分弹窗
          if (!hasEvaluated) {
            this.setData({ showScoreModal: true });
          } else {
            wx.showToast({
              title: "全部课程已看完！",
              icon: "success",
              duration: 3000
            });
          }
        }, 1000);
      } else {
        this.setData({ currentVideoIndex: currentVideoIndex + 1 }, () => {
          setTimeout(() => {
            this.videoContext = wx.createVideoContext("videoPlayer", this);
            this.videoContext.play();
          }, 300);
        });
      }
    },
  
    changePlaybackRate(e) {
      const rateIndex = e.detail.value;
      const rate = this.data.playbackRates[rateIndex];
      this.setData({ currentRate: rate, currentRateIndex: rateIndex });
      if (this.videoContext) {
        this.videoContext.setPlaybackRate(rate);
      }
    },
  
    onFullScreenChange(e) {
      console.log("全屏状态变化：", e.detail.fullScreen);
    },
  
    toggleBannerZoom() {
      this.setData({
        isBannerZoom:!this.data.isBannerZoom,
        autoPlay:!this.data.isBannerZoom
      });
    },
  
    onVideoError(e) {
      console.error("视频错误：", e.detail.errMsg);
      wx.showToast({ title: "视频加载失败", icon: "none" });
    },
  
    onVideoPlay() {
      console.log("视频开始播放");
    },
  
    onVideoPause() {
      console.log("视频已暂停");
    },
  
    closeVipTipModal() {
      this.setData({ showVipTipModal: false });
    },
  
    openVipConfirmModal() {
      this.setData({ showVipTipModal: false });
      this.setData({ showVipConfirmModal: true });
    },
  
    closeVipConfirmModal() {
      this.setData({ showVipConfirmModal: false });
    },
  
    confirmOpenVip() {
      wx.showLoading({ title: '开通中...' });
  
      setTimeout(() => {
        const userInfo = wx.getStorageSync('userInfo') || {};
        userInfo.isVip = true;
        wx.setStorageSync('userInfo', userInfo); 
        this.setData({
          isVip: true,
          showVipConfirmModal: false,
          showVipTipModal: false
        });
  
        if (this.data.showVideoModal) {
          this.closeVideoModal();
        }
  
        wx.showToast({
          title: '会员开通成功',
          icon: 'success',
          duration: 2000
        });
      }, 1500);
    },
  
    onShow() {
      const hasToken =!!wx.getStorageSync('token');
      if (!hasToken) {
        wx.removeStorageSync('userInfo');
        this.setData({ isVip: false });
      } else {
        this.checkVipStatus();
      }
    },
  
    openReviewModal() {
      this.setData({
        showReviewModal: true,
        commentContent: ""
      });
    },
  
    closeReviewModal() {
      this.setData({
        showReviewModal: false,
        commentContent: ""
      });
    },
  
    onCommentInput(e) {
      this.setData({
        commentContent: e.detail.value
      });
    },
  
    submitComment() {
      const { commentContent, isVip, courseId } = this.data;
      if (!commentContent.trim()) {
        wx.showToast({ title: '评论内容不能为空', icon: 'none' });
        return;
      }
      if (!isVip) {
        wx.showToast({ title: '您不是VIP，无法发表评论', icon: 'none' });
        return;
      }
      
      const token = wx.getStorageSync('token') || '';
      const targetId = courseId; 
      const userInfo = wx.getStorageSync('userInfo') || {};
      const userId = userInfo.id || ''; 
      if (!userId) {
        wx.showToast({ title: '未获取到用户信息', icon: 'none' });
        return;
      }
  
      const now = new Date();
      const year = now.getFullYear();
      const month = (now.getMonth() + 1).toString().padStart(2, '0');
      const day = now.getDate().toString().padStart(2, '0');
      const hour = now.getHours().toString().padStart(2, '0');
      const minute = now.getMinutes().toString().padStart(2, '0');
      const second = now.getSeconds().toString().padStart(2, '0');
      const createTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  
      const requestData = {
        userId: userId,        
        targetType: 1,        
        targetId: targetId,   
        content: commentContent,
        likeCount: 0,
        createTime: createTime, 
      };
  
      wx.showLoading({ title: '发布中...' });
  
      wx.request({
        url: 'http://localhost:8080/course/comments',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`, 
          'content-type': 'application/json'
        },
        data: requestData,
        success: (res) => {
          console.log("评论接口返回：", res.data);
          if (res.statusCode === 200 && res.data.code === 200) {
            wx.showToast({ 
              title: '评论发表成功', 
              icon: 'success',
              duration: 1500 
            });
            
            this.closeReviewModal();
            
            setTimeout(() => {
              this.fetchCourseDetail(courseId, true);
            }, 800);
            
          } else {
            wx.showToast({ title: res.data.msg || '评论发表失败', icon: 'none' });
            if (res.data.code === 401) { 
              wx.removeStorageSync('token');
              wx.removeStorageSync('userInfo');
              wx.navigateTo({ url: '/pages/login/login' });
            }
            console.error('评论接口异常：', res);
          }
        },
        fail: (err) => {
          wx.showToast({ title: '请求失败', icon: 'none' });
          console.error('评论接口请求失败：', err);
        },
        complete: () => {
          wx.hideLoading();
        }
      });
    },
  
    cancelComment() {
      this.closeReviewModal();
    },
  
    onPullDownRefresh() {
      if (this.data.courseId) {
        this.fetchCourseDetail(this.data.courseId, true).then(() => {
          wx.stopPullDownRefresh();
        });
      } else {
        wx.stopPullDownRefresh();
      }
    },
  
    // 评分相关方法 - Vant组件适配
    onScoreChange(event) {
      this.setData({
        selectedScore: event.detail
      });
    },
  
    submitScore() {
      const { selectedScore, courseId, isVip, hasEvaluated } = this.data;
      if (hasEvaluated) {
        wx.showToast({ title: '您已评价过该课程', icon: 'none' });
        return;
      }
      
      const userInfo = wx.getStorageSync('userInfo') || {};
      const userId = userInfo.id;
  
      if (selectedScore === 0) {
        wx.showToast({ title: '请选择评分', icon: 'none' });
        return;
      }
      if (!isVip) {
        wx.showToast({ title: '您不是VIP，无法评分', icon: 'none' });
        return;
      }
  
      const token = wx.getStorageSync('token') || '';
      const requestData = {
        userId: userId,
        coursesId: courseId,
        score: selectedScore,
      };
  
      wx.showLoading({ title: '提交中...' });
      wx.request({
        url: 'http://localhost:8080/course/score',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'content-type': 'application/json',
        },
        data: requestData,
        success: (res) => {
          wx.hideLoading();
          if (res.statusCode === 200 && res.data.code === 200) {
            wx.showToast({ title: '评分成功', icon: 'success' });
            this.setData({ 
              showScoreModal: false, 
              selectedScore: 0,
              hasEvaluated: true
            });
            this.fetchCourseDetail(courseId, true);
          } else if (res.data.code === 400) {
            wx.showToast({ title: '您已评价过该课程', icon: 'none' });
            this.setData({ 
              showScoreModal: false,
              hasEvaluated: true
            });
          } else {
            wx.showToast({ title: '评分失败', icon: 'none' });
            console.error('评分接口异常：', res);
          }
        },
        fail: (err) => {
          wx.hideLoading();
          wx.showToast({ title: '网络请求失败', icon: 'none' });
          console.error('评分接口请求失败：', err);
        },
      });
    },
  
    closeScoreModal() {
      this.setData({ showScoreModal: false });
    }
  });
